package com.example.easytts.service

import com.example.easytts.model.User
import com.example.easytts.repository.UserRepository
import com.example.easytts.security.JwtUtil
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
import org.slf4j.LoggerFactory

@Service
class UserService(
    private val userRepository: UserRepository
) {
    private val logger = LoggerFactory.getLogger(UserService::class.java)
    private val passwordEncoder = BCryptPasswordEncoder()

    fun register(username: String, password: String): Boolean {
        if (userRepository.findByUsername(username) != null) return false
        val user = User(username = username, password = passwordEncoder.encode(password))
        userRepository.save(user)
        return true
    }

    fun login(username: String, password: String): String? {
        val user = userRepository.findByUsername(username) ?: return null
        return if (passwordEncoder.matches(password, user.password)) {
            JwtUtil.generateToken(user.username, listOf(user.role))
        } else null
    }

    fun getUserIdFromToken(authHeader: String): Long? {
        val token = if (authHeader.startsWith("Bearer ")) authHeader.substring(7) else authHeader
        val username = JwtUtil.getUsername(token) ?: return null
        val user = userRepository.findByUsername(username)
        return user?.id
    }
}